import { defineComponent, computed, ref } from 'vue'
import { omit } from 'lodash-es'
import { VxeGridInstance, VxeGridEventProps, VxeGrid } from 'vxe-table'
import XEUtils from 'xe-utils'

import { BasicGridProps } from './types'
import { basicProps } from './props'
import { basicEmits } from './emits'

import { extendSlots } from '@/utils'

export default defineComponent({
  name: 'VxeGrid',
  props: basicProps,
  emits: basicEmits,
  setup(props, { attrs, emit }) {
    const $grid = ref<VxeGridInstance>()
    const emitEvents: VxeGridEventProps = {}

    basicEmits.forEach((name) => {
      const type = XEUtils.camelCase(`on-${name}`) as keyof VxeGridEventProps

      emitEvents[type] = (...args: any[]) => emit(name, ...args)
    })

    const getBindGridEvent: VxeGridEventProps = {
      ...emitEvents
    }

    const getBindValues = computed<BasicGridProps>(() => {
      const propsData: BasicGridProps = {
        ...attrs,
        ...props
      }

      return propsData
    })

    const getBindGridValues = computed(() => {
      const omitProps = omit(getBindValues.value, [])

      return {
        ...omitProps,
        ...getBindGridEvent
      }
    })

    const tableExpose = {
      getBindGridValues,
      $grid
    }

    return tableExpose
  },
  render() {
    return (
      <VxeGrid ref="$grid" {...this.getBindGridValues}>
        {extendSlots(this.$slots)}
      </VxeGrid>
    )
  }
})
